<template>
  <div
    class="editor"
    :ref="state.editorRef"
    :class="[state.editorClassName]"
    v-if="state.type !== 'view'"
  ></div>
  <div class="goods-content" v-else v-html="state.value"></div>
</template>
<script>
import {
  defineComponent,
  onMounted,
  reactive,
  watch,
  computed,
  nextTick,
} from "vue";
import { useStore } from "vuex";
import moment from "moment";
import E from "wangeditor";
import { generateUUID } from "@/utils/index";
import { getUploadUrl, uploadFile } from "@/utils/index";
const ossSrc = import.meta.env.VITE_APP_OSS_SRC;

export default defineComponent({
  components: {},
  props: {
    value: {
      type: String,
      default: null,
    },
    type: {
      type: String,
      default: "",
    },
    options: {
      type: Object,
      default: () => {},
    },
    elFormItem: {
      type: Object,
      default: () => {},
    },
  },
  emits: ["update:value"],
  setup(props, { emit }) {
    const Store = useStore();
    const state = reactive({
      editorRef: (el) => (state.elEditor = el),
      elEditor: null,
      editorContent: "",
      editorClassName: "",
      editor: null,
      value: computed(() => props.value),
      options: computed(() => props.options),
      type: computed(() => props.type),
      elFormItem: computed(() => props.elFormItem),
    });
    onMounted(async () => {
      methods.initE();
    });
    const methods = {
      initE() {
        state.editorClassName = `editor_${parseInt(
          Math.random() * 999999999
        )}_${document.querySelectorAll("*").length}`;
        nextTick(() => {
          let elEditor = document.querySelector(`.${state.editorClassName}`);
          if (elEditor) {
            state.editor = new E(elEditor);
            state.editor.config.zIndex = 1;
            state.editor.config.uploadImgMaxLength = 5;
            state.editor.config.onchange = function (html) {
              state.editorContent = html;
              emit("update:value", state.editorContent);
              nextTick(() => {
                state.elFormItem && state.elFormItem.onFieldChange();
              });
            };

            state.editor.config.customUploadImg = async (files, cb) => {
              try {
                await Promise.all(
                  files.map((file) => {
                    return new Promise((resolve, reject) => {
                      const { name } = file;
                      const key = `/static/images/${moment().format(
                        "yyyy-MM-DD"
                      )}/${generateUUID()}___${name}`;
                      getUploadUrl({ key })
                        .then(({ url }) => {
                          url = url.replace(/^http:/, "https:");
                          uploadFile(url, file)
                            .then(() => {
                              try {
                                const fileSrc = url.split("?")[0];
                                let imgSrc = `${ossSrc}${fileSrc
                                  .split(".myqcloud.com")
                                  .pop()}`;
                                cb(imgSrc, name);
                                resolve();
                              } catch (error) {
                                reject(error);
                              }
                            })
                            .catch(reject);
                        })
                        .catch(reject);
                    });
                  })
                );
              } catch (error) {
                message.error(error.message);
              }
            };

            state.editor.config.linkImgCallback = (src, alt, href) => {
              console.log(src, alt, href);
            };

            state.editor.create();
          }
        });
      },
      dispatchChange() {
        setTimeout(() => {
          debugger;
          var event = document.createEvent("HTMLEvents");
          event.initEvent("change", true, true);
          document
            .querySelector(`.${state.editorClassName}`)
            .dispatchEvent(event);
          state.elEditor && state.elEditor.dispatchEvent(event);
        });
      },
    };
    watch(
      () => state.value,
      (val, old) => {
        if (val !== state.editorContent) {
          if (state.type !== "view") {
            state.editor.txt.html(val);
          }

          state.editorContent = val;
        }
      }
    );
    window.wEditorState = state;
    return {
      ...methods,
      state,
    };
  },
});
</script>
<style lang="less" scoped>
.goods-content {
  padding-top: 5px;
}
</style>
